package com.xxw.yygh.hosp.controller.api;

import com.xxw.yygh.common.exception.YyghException;
import com.xxw.yygh.common.utils.MD5;
import com.xxw.yygh.hosp.bean.Result;
import com.xxw.yygh.hosp.service.HospitalService;
import com.xxw.yygh.hosp.utils.HttpRequestHelper;
import com.xxw.yygh.model.hosp.Hospital;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("/api/hosp")
public class ApiHospitalController {

    @Resource
    private HospitalService hospitalService;

    //第三方医院上传（新增）
    @PostMapping("/saveHospital")
    public Result saveHospital(HttpServletRequest request){
        //获取所有的参数
        Map<String, String[]> parameterMap = request.getParameterMap();
        Map<String, Object> resultMap = HttpRequestHelper.switchMap(parameterMap);
        //拿到第三方医院的秘钥在根据hoscode查本地存储的秘钥
        String requestSignKey = (String) resultMap.get("sign");
        String requestHoscode = (String) resultMap.get("hoscode");
        String platformSignKey =hospitalService.getSignKeyWithHoscode(requestHoscode);

        //对秘钥进行加密
        String encrypt = MD5.encrypt(platformSignKey);
        //判断：秘钥不为空且相等才能进入
        if (!StringUtils.isEmpty(requestSignKey) && !StringUtils.isEmpty(encrypt) && encrypt.equals(requestSignKey)){
            //传输过程中base64加密图片数据还原：" " 换成 "+"
            String logoData = (String) resultMap.get("logoData");
            String result = logoData.replaceAll(" ", "+");
            resultMap.put("logoData",result);
            //保存
            hospitalService.saveHospital(resultMap);
            return Result.ok();
        }else {
            throw  new YyghException(20001,"保存失败");
        }
    }

    //查询第三方医院列表展示
    @PostMapping("/hospital/show")
    public Result<Hospital> getHospitalInfo(HttpServletRequest request){
        Map<String, Object> stringObjectMap = HttpRequestHelper.switchMap(request.getParameterMap());
        String hoscode = (String) stringObjectMap.get("hoscode");
        Hospital hospital=hospitalService.getHospitalByHoscode(hoscode);

        return Result.ok(hospital);
    }

}
